package com.awesome.spring.netty.handler;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: u-social
 * @description: 集群队列Server
 * @author: Alex Wu
 * @createDate: 2025-03-17 16:00
 **/
public class RedisChatServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static final Map<String, Channel> LOCAL_CHANNELS = new ConcurrentHashMap<>();
    private static final String REDIS_USER_SERVER_KEY = "user_server";
    public static final String SERVER_ID = UUID.randomUUID().toString(); // 当前服务器 ID
    private final StringRedisTemplate redisTemplate;

    public RedisChatServerHandler(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        String userId = (String) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (userId != null) {
            LOCAL_CHANNELS.put(userId, ctx.channel());
            redisTemplate.opsForHash().put(REDIS_USER_SERVER_KEY, userId, SERVER_ID);
        }
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        String userId = (String) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (userId != null) {
            LOCAL_CHANNELS.remove(userId);
            redisTemplate.opsForHash().delete(REDIS_USER_SERVER_KEY, userId);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) {
        String text = msg.text();
        JSONObject json = JSONObject.parseObject(text);
        String targetUserId = json.getString("toUserId");
        String message = json.getString("message");

        // 先检查本机是否有该用户的连接
        Channel targetChannel = LOCAL_CHANNELS.get(targetUserId);
        if (targetChannel != null) {
            targetChannel.writeAndFlush(new TextWebSocketFrame(message));
        } else {
            // 通过 Redis 查找该用户在哪个服务器
            String targetServerId = (String) redisTemplate.opsForHash().get(REDIS_USER_SERVER_KEY, targetUserId);
            if (targetServerId != null) {
                redisTemplate.convertAndSend("chat_channel", targetServerId + ":" + targetUserId + ":" + message);
            }
        }
    }
}
